package com.xf.tourismapp.services;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import com.xf.tourismapp.R;

/**
 * 执行后台音乐播放任务服务
 */
public class MusicService extends Service  {

    private MediaPlayer player; //媒体播放器MediaPlayer
    private static final  String TAG="DEBUG_INFO";

    @Override
    public void onCreate() {
        super.onCreate();
        initPlayer();
    }

    //初始MediaPlayer
    private void initPlayer()
    {
        try {
            //播放音乐，初始化媒体播放器 MediaPlayer
            player=MediaPlayer.create(getApplicationContext(), R.raw.apologize );
            player.prepare();  //资源播放准备
            player.setLooping(true); //音乐自动循环播放
        } catch (Exception e) {
            Log.i(TAG,"播放器异常");
        }
    }
    //控制音乐开始播放和暂停方法
    public void playOrPause()
    {
        if (player != null) {
            if (player.isPlaying()) {//当前是播放状态
                player.pause(); //暂停
            } else {//当前是暂停状态
                player.start(); //播放
            }
        }else
        {
            initPlayer();
            player.start(); //播放
        }
    }

    //控制音乐停止的方法
    public void stop()
    {
        if (player != null) {
            player.pause();
            player.seekTo(0);
        }
    }

    //跳转到指定位置播放
    public void seekTo(int pos)
    {
        if (player != null) {
            player.seekTo(pos);
        }
    }

    //获取播放器状态
    public boolean isPlaying()
    {
        if (player != null) {
            return player.isPlaying();
        }else
        {
            return false;
        }
    }

    //获取音乐总时长
    public int getDuration()
    {
        if (player != null) {
            return player.getDuration();
        }else
        {
            return 0;
        }
    }

    //获取音乐当前播放进度
    public int getCurrentPosition()
    {
        if (player != null) {
            return player.getCurrentPosition();
        }else
        {
            return 0;
        }
    }


    public class MyBinder extends Binder
    {
        public MusicService getService()
        {
            return MusicService.this;  //返回MusicService对象到Activity中
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(player!=null)
        {
            player.release();
            player = null;
        }
    }
}